<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:shopCategory:add']"
        >添加</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopCategoryList" row-key="id" @selection-change="handleSelectionChange">
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="图标" align="center" prop="icon">
        <template slot-scope="scope">
          <ImagePreview
            :width=100 :height=100
            :src="scope.row.iconOssUrl"
            :preview-src-list="[scope.row.iconOssUrl]"/>
        </template>
      </el-table-column>
      <el-table-column label="顺序" align="center" prop="sort" />
      <el-table-column label="显示在首页" align="center" prop="showIndex">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.showIndex"
            @change="changeShowIndex(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="Banner管理">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-picture" @click.native="bannerMgr(scope.row)">管理</el-button>
        </template>
      </el-table-column>
      <el-table-column label="属性管理">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-s-operation" @click.native="attrKeyMgr(scope.row)">管理</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:shopCategory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:shopCategory:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品类别对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="父类别" prop="pid">
              <el-select v-model="form.pid" placeholder="请选择父类别">
                <el-option v-for="item in rootList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" minlength="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标" prop="icon">
              <imageUpload v-model="imageUploadValue" :limit="1" @fileList="getImageUrl"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="顺序" prop="sort">
              <el-input type="number" v-model="form.sort"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="链接地址" prop="url">
              <el-input v-model="form.url" placeholder="请输入链接地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示在首页" prop="showIndex">
              <el-radio-group v-model="form.showIndex">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" :rows="2" v-model="form.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="Banner管理"
      :visible.sync="banner.visible"
      width="70%">
      <el-tabs v-model="banner.activeName">
        <el-tab-pane label="管理" name="first">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click.native="addBanner">添加</el-button>
          <el-table :data="banner.list" v-loading="loading" border>
            <el-table-column label="标题">
              <template slot-scope="scope">
                {{scope.row.title}}
              </template>
            </el-table-column>
            <el-table-column label="url">
              <template slot-scope="scope">
                {{scope.row.url}}
              </template>
            </el-table-column>
            <el-table-column label="图片">
              <template slot-scope="scope">
                <ImagePreview
                  :width=100 :height=100
                  :src="scope.row.ossUrl"
                  :preview-src-list="[scope.row.ossUrl]"/>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" icon="el-icon-delete" @click.native="bannerRemove(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="预览" name="second">
          <el-carousel indicator-position="outside">
            <el-carousel-item v-for="itemBanner in banner.list" :key="itemBanner.id">
              <img :src="itemBanner.ossUrl" style="width:100%;">
            </el-carousel-item>
          </el-carousel>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <el-dialog
      title="属性管理"
      :visible.sync="attrKey.visible"
      width="70%">
      <el-row>
        <el-col :span="24">
          <el-button type="success" size="mini" icon="el-icon-plus" @click.native="attrKeyAdd" v-hasPermi="['shop:shopCategory:edit']">添加</el-button>
        </el-col>
      </el-row>
      <el-table :data="attrKey.list" v-loading="loading" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column label="属性名">
          <template slot-scope="scope">
            {{scope.row.attrName}}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click.native="attrKeyEdit(scope.row)">编辑</el-button>
            <el-button type="primary" size="mini" icon="el-icon-edit" @click.native="openAttrValDialog(scope.row)">编辑属性值</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click.native="attrKeyRemove(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      title="属性值管理"
      :visible.sync="attrVal.visible"
      width="50%">
      <el-row>
        <el-row>
          <el-col :span="24">
            <el-button type="success" size="mini" icon="el-icon-plus" @click.native="attrValAdd" v-hasPermi="['shop:shopCategory:edit']">添加</el-button>
          </el-col>
        </el-row>
        <el-table :data="attrVal.list" v-loading="loading" element-loading-text="Loading" border fit highlight-current-row>
          <el-table-column label="属性值">
            <template slot-scope="scope">
              {{scope.row.attrVal}}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click.native="attrValEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click.native="attrValRemove(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { listShopCategory, getShopCategory, delShopCategory, addShopCategory, updateShopCategory, changeShowIndex, getBanners, removeBanner, getAttrKeys } from "@/api/shop/shopCategory";
import { delShopAttrKey, addShopAttrKey, updateShopAttrKey } from "@/api/shop/shopAttrKey";
import { delShopAttrVal, addShopAttrVal, updateShopAttrVal, getAttrVals } from "@/api/shop/shopAttrVal";

export default {
  name: "ShopCategory",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品类别表格数据
      shopCategoryList: [],
      rootList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pid: undefined,
        name: undefined,
        sort: undefined,
        icon: undefined,
        url: undefined,
        isDelete: undefined,
        showIndex: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "顺序不能为空", trigger: "blur" }
        ],
        iconOssId: [
          { required: true, message: "图标ID不能为空", trigger: "blur" }
        ],
        iconOssUrl: [
          { required: true, message: "图标URL不能为空", trigger: "blur" }
        ],
        showIndex: [
          { required: true, message: "是否显示在首页不能为空", trigger: "blur" }
        ]
      },
      banner: {
        idCategory: '',
        activeName: 'first',
        visible: false,
        list: []
      },
      attrKey: {
        idCategory: '',
        visible: false,
        list: []
      },
      attrVal: {
        idAttrKey: '',
        visible: false,
        list: []
      },
      imageUploadValue: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商品类别列表 */
    getList() {
      this.loading = true;
      listShopCategory(this.queryParams).then(response => {
        this.shopCategoryList = response.data;
        this.rootList = Object.assign({},response.data)
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.imageUploadValue=[];
      this.form = {
        id: undefined,
        pid: undefined,
        name: undefined,
        sort: undefined,
        iconOssId: undefined,
        iconOssUrl: undefined,
        url: undefined,
        isDelete: undefined,
        showIndex: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品类别";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getShopCategory(id).then(response => {
        this.loading = false;
        this.form = response.data;
        if(this.form.iconOssId){
          this.imageUploadValue = [{ossId: this.form.iconOssId,url: this.form.iconOssUrl}];
        }
        this.open = true;
        this.title = "修改商品类别";
        console.info(this.form)
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateShopCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addShopCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品类别编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delShopCategory(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('shop/shopCategory/export', {
        ...this.queryParams
      }, `shopCategory_${new Date().getTime()}.xlsx`)
    },
    changeShowIndex(data) {
      if (data.pid) {
        this.$message({
          message: '二级菜单不支持该操作',
          type: 'warning'
        })
        data.showIndex = false
        return
      }
      changeShowIndex(data.id, data.showIndex).then(response => {
        this.$modal.msgSuccess("操作成功");
      })
    },
    bannerMgr(data) {
      if (data.pid) {
        this.$message({
          message: '二级菜单不支持该操作',
          type: 'warning'
        })
        data.showIndex = false
        return
      }
      this.banner.visible = true
      this.banner.idCategory = data.id
      getBanners(data.id).then(response => {
        this.banner.list = response.data
        console.log('banner', this.banner)
      })
    },
    addBanner() {
      this.banner.visible = false;
      this.$router.push({ path: 'shopBanner', query: {idCategory: this.banner.idCategory}})
    },
    bannerRemove(id) {
      removeBanner(this.banner.idCategory, id).then(response => {
        this.$modal.msgSuccess("操作成功");
        getBanners(this.banner.idCategory).then(response => {
          this.banner.list = response.data
          console.log('banner', this.banner)
        })
      })
    },
    attrKeyMgr(data) {
      this.attrKey.visible = true
      this.attrKey.idCategory = data.id
      getAttrKeys(data.id).then(response => {
        this.attrKey.list = response.data
        console.log('attrKey', this.attrKey)
      })
    },
    attrKeyAdd() {
      this.$prompt('请输入属性名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        if (!value || value === '') {
          this.$message({
            type: 'warning',
            message: '属性名不能为空'
          })
        }
        addShopAttrKey({attrName: value, idCategory: this.attrKey.idCategory}).then(response => {
          this.$modal.msgSuccess("新增属性成功");
          getAttrKeys(this.attrKey.idCategory).then(response => {
            this.attrKey.list = response.data
            console.log('attrKey', this.attrKey)
          })
        });
      })
    },
    attrKeyEdit(item) {
      console.log('item', item)
      this.$prompt('请输入属性名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.attrName,
      }).then(({value}) => {
        if (!value || value === '') {
          this.$message({
            type: 'warning',
            message: '属性名不能为空'
          })
        }
        updateShopAttrKey({attrName: value, idCategory: this.attrKey.idCategory,id: item.id}).then(response => {
          item.attrName = value
          this.$message({
            type: 'success',
            message: '编辑成功'
          })
        })
        return
      })
    },
    attrKeyRemove(id) {
      console.log('id', id)
      delShopAttrKey(id).then(response => {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        getAttrKeys(this.attrKey.idCategory).then(response => {
          this.attrKey.list = response.data
          console.log('attrKey', this.attrKey)
        })
      })

    },
    openAttrValDialog(item) {
      this.attrVal.idAttrKey = item.id
      this.attrVal.visible = true
      console.log('item', item)
      getAttrVals(this.attrVal.idAttrKey).then(response => {
        this.attrVal.list = response.data
      })
    },
    attrValAdd() {
      this.$prompt('请输入属性名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        if (!value || value === '') {
          this.$message({
            type: 'warning',
            message: '属性名不能为空'
          })
        }
        addShopAttrVal({attrVal: value, idAttrKey: this.attrVal.idAttrKey}).then(response => {
          this.$modal.msgSuccess("新增属性成功");
          getAttrVals(this.attrVal.idAttrKey).then(res => {
            this.attrVal.list = res.data
          })
        });
      })
    },
    attrValEdit(item) {
      console.log('item', item)
      this.$prompt('请输入属性名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.attrVal,
      }).then(({value}) => {
        if (!value || value === '') {
          this.$message({
            type: 'warning',
            message: '属性名不能为空'
          })
        }
        updateShopAttrVal({attrVal: value, idAttrKey: this.attrVal.idAttrKey, id: item.id}).then(response => {
          this.$modal.msgSuccess("修改成功");
          getAttrVals(this.attrVal.idAttrKey).then(res => {
            this.attrVal.list = res.data
          })
        });
        return
      })
    },
    attrValRemove(id) {
      console.log('id', id)
      delShopAttrVal(id).then(response => {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        getAttrVals(this.attrVal.idAttrKey).then(res => {
          this.attrVal.list = res.data
        })
      })
    },
    getImageUrl(fileList){
      if(fileList.length == 1){
        this.form.iconOssId = fileList[0].ossId;
        this.form.iconOssUrl = fileList[0].url;
      }else{
        this.form.iconOssId = "";
        this.form.iconOssUrl = "";
      }
    },
  }
};
</script>
